#include "headfile.h"
#include "communicate.h"

union data_send_float
{
  float data;
  uint8_t send[4];
};

struct buffer
{
  uint8_t in; // 写入
  uint8_t out; // 读出
  uint8_t my_buff[BUFF_MAX_SIZE];
}uart_buff = {0, 0, {0}},send_buff = {0, 0, {0}};

bool is_buffer_full(struct buffer *buf)
{
  if(((buf->in+1) % BUFF_MAX_SIZE) == buf->out)
    return true;  // 已满
  return false;
}

bool is_buffer_empty(struct buffer *buf)
{
  if(buf->out == buf->in)
    return true;  // 已空
  return false;
}

bool write_buffer(struct buffer *buf, uint8_t *data)
{
  if(is_buffer_full(buf))
    return false;  // 写入失败
  buf->my_buff[buf->in] = *data;
  buf->in = (++buf->in) % BUFF_MAX_SIZE;
  return true;  // 写入成功
}

bool read_buffer(struct buffer *buf, uint8_t *data)
{
  if(is_buffer_empty(buf))
    return false;  // 读取失败
  *data = buf->my_buff[buf->out];
  buf->out = (++buf->out) % BUFF_MAX_SIZE;
  return true;  // 读取成功
}

uint8_t get_buffer_len(struct buffer *buf)
{
  return (buf->in - buf->out + BUFF_MAX_SIZE) % BUFF_MAX_SIZE;
}

uint8_t read_several_buffer(struct buffer *buf,uint8_t *read_arry,uint8_t len)
{
  uint8_t current_len = get_buffer_len(buf);
  if(len>current_len)
    return false;  // 读取失败
  for(uint8_t i=0;i<len;i++)
  {
    read_buffer(buf,&read_arry[i]);
  }
  return true;  // 读取成功
}

void clear_buffer()
{
  uint8_t junk;
  while(is_buffer_empty(&uart_buff)==false)
  {
    read_buffer(&uart_buff,&junk);
  }
}
